﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SpectationClient.DataBaseDescription;


namespace SpectationClient.DGVExtensions {

    public interface IDatagridViewExtensionBaseCell { 
        IColumnInfo ColumnInfo {get;}
        TableInfo TableInfo { get; }
    }

    public abstract class DataGridViewExtensionBaseCell : DataGridViewTextBoxCell, IDatagridViewExtensionBaseCell {

        protected bool dataBaseDescriptionChecked = false;
        protected IColumnInfo columnInfo = null;
        protected TableInfo tableInfo = null;

        protected virtual void setDatabaseDescriptions() {
            if(!dataBaseDescriptionChecked) {
                DataGridViewExtensionBaseColumn bcol = this.DataGridView.Columns[this.ColumnIndex] as DataGridViewExtensionBaseColumn;
                if(bcol != null && bcol.ColumnInfo != null) {
                    columnInfo = bcol.ColumnInfo;
                    tableInfo = bcol.TableInfo;
                }
                dataBaseDescriptionChecked = true;
            }
        }
        public virtual IColumnInfo ColumnInfo {
            get {
                setDatabaseDescriptions();
                return this.columnInfo;
            }
        }
           
        public TableInfo TableInfo {
            get {
                setDatabaseDescriptions();
                return this.tableInfo;
            }
        }

        protected override bool SetValue(int rowIndex, object value) {
            return base.SetValue(rowIndex, value);
        }

        /// <summary>
        /// Returns the row ID values. This required that the DataGridViewColumn is
        /// initialized with a ColumnInfo that is part of a TableInfo.
        /// </summary>
        /// <returns></returns>
        public Object[] getRowID() {
            if(this.TableInfo == null || !this.TableInfo.hasPK) return null;

            return (from String name in this.TableInfo.PrimaryKey.Names
                    select this.DataGridView[name, this.RowIndex].Value).ToArray();
        }


        protected T getRowValue<T>(String columnName) {
            if(this.OwningRow.Cells[columnName].Value == DBNull.Value) return default(T);
            return (T)this.OwningRow.Cells[columnName].Value;
        }


    }

}
